import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Input,
  Radio,
  Upload,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import http from '../../utils/http'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'
import { MdEditor } from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import { useEffect, useRef, useState } from 'react'
const Publish = ()=> {
  //回填数据
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')??''
  const [form] = Form.useForm()
  //频道列表
  const [ channelList, setChannelList ] = useState([])
  useEffect(() => {
    const fetchannels = async () => {
      const res = await http.get('/channels')
      setChannelList(res.data.channels)
    }
    fetchannels()
  },[])
  //编辑回填
  useEffect(() => {
    const getArticle = async () => {
      const res = await http.get(`/mp/articles/${articleId}`)
      const {  cover, ...formValue } = res.data
      form.setFieldsValue({ ...formValue, type: cover.type })
      setValue(res.data.content)
      setImageType(cover.type)
      setImageList(cover.images.map(item => ({ url: item })))
    }
    getArticle()
  },[articleId])
  // 控制图片Type
  const [imageType, setImageType] = useState(1)
  const [value, setValue] = useState('')
  const onRadioChange  = (e) => {
    const type = e.target.value
    setImageType(e.target.value)
    if(type === 1){
      //单图，截取第一张
      const imgList = cacheImagelist.current[0]
      setImageList([imgList])
    }else if(type === 3){
      //多图，截取所有
      setImageList(cacheImagelist.current)
    }
  }
  //发布文章
  const onFinish = async (values) => {
    if (imageType !== imageList.length) return message.warning('图片类型和数量不一致')
    const { channel_id, title } = values
    const params = {
      channel_id,
      content: value,
      title,
      cover: {
        type: imageType,
        images: imageList.map(item => item?.response?.data?.url??item.url)
      }
    }
    if(articleId){
      await http.put(`/mp/articles/${articleId}?draft=false`, params)
    }else{
      await http.post('/mp/articles?draft=false', params)
    }
    message.success(`${articleId ? '编辑' : '发布'}文章成功`)
  }
  //上传图片
  const cacheImagelist = useRef([])
  const [imageList, setImageList] = useState([])
  const onUploadChange = ({ fileList: newFileList }) =>{
    setImageList(newFileList)
    cacheImagelist.current = newFileList
  }
    return (
      <div className="Publish">
        <Card title={<Breadcrumb items={[
          { title: <Link to={'/'}>首页</Link> },
          { title: articleId ? '编辑文章' : '发布文章' }
          ]} />}>
        <Form 
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type:1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item 
            label="文章标题" name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
            >
            <Input placeholder='请输入文章标题' style={{ width: '400px' }} />
          </Form.Item>
          <Form.Item 
            label="频道" name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
            >
            <Select placeholder='请选择文章频道' style={{ width: '400px' }}
            options={channelList.map(item => ({ label: item.name, value: item.id }))}
            />
          </Form.Item>
          <Form.Item
            label="内容"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
          <MdEditor value={value} onChange={setValue} preview={false} />
          </Form.Item>
          <Form.Item label="封面" name='type'>
            <div>
              <Radio.Group style={{marginTop: '6px'}} onChange={onRadioChange} value={imageType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
          {/* </Form.Item> */}
          <Form.Item style={{ marginTop: '10px',marginBottom: '0' }}>
              { imageType > 0 && (
                <Upload
                name="image"
                listType="picture-card"
                showUploadList
                action='http://geek.itheima.net/v1_0/upload'
                onChange={onUploadChange}
                maxCount={imageType}
                multiple={imageType > 1}
                fileList={imageList}
              >
                  <PlusOutlined />
              </Upload>
              )}
          </Form.Item>
            {/* </Form.Item> */}
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" htmlType="submit">{articleId ? '更新文章' : '发布文章'}</Button> 
          </Form.Item>
        </Form>
        </Card>
      </div>
    )
  }
  export default Publish